import _ from 'underscore';
import classnames from 'classnames';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import Card from 'lib/components/card.jsx';
import { defaultApi, defaultPostApi } from '../../apis/core-util';
import ReactPages from 'react-pagers';
import { Link } from 'react-router';
import Loading from 'lib/util/defaultLoadingElement.jsx';
import { formatByValue } from '../Constants.es6';
import query from 'lib/util/QueryStore.es6';

let translator = (value) => {
  if (value === 0) {
    return '否';
  } else if (value === 1) {
    return '是';
  } else if (value === '' || _.isNull(value)) {
    return '<span data-place="right" data-tip="没有设定该属性的值时，归为未知"><span class="value-unknown">未知</span></span>';
  } else if (_.isArray(value)) {
    return value.join(', ');
  } else {
    return value;
  }
};

let PopoverCard = ({properties}) => {
  return (
    <div className="popover-content">
      <table className="sequence-prop">
        <tbody>
          {
            _.map(properties, (property, index) => {
              return (
                <tr key={ index }>
                  {
                    _.map(property, (item, key) => {
                      return (
                        [
                          <td key={ item.cname }>{ item.cname }：</td>,
                          <td key={ item.value }>{ item.value }</td>
                        ]
                      )
                    })
                  }
                </tr>
              )
            })
          }
        </tbody>
      </table>
    </div>
  );
};

let covert = (h, events, eventProps) => {
    var properties = [];

    var b = function(key, object) {
        var i = -1;
        $.each(object, function(index, item) {
            if (key === item.name) {
                i = index;
            }
        });
        return i;
    };
    var g = [];

    for (var e in events[h].properties) {
        if (events[h].properties.hasOwnProperty(e)) {
            var c = b(e, eventProps);
            var temp = {
                name: eventProps[c].name,
                cname: eventProps[c].cname,
                mark: events[h].mark,
                data_type: eventProps[c].data_type
            };

            temp.value = formatByValue(temp.data_type, events[h].properties[e]);

            if (g.length < 2) {
                g.push(temp);
            } else {
                properties.push(g);
                g = [];
                g.push(temp);
            }
        }
    }
    properties.push(g);

    return properties;
};

class UserSequenceView extends React.Component {

  constructor(props){
    super(props);

    this.state = {
      events: [],
      eventLoading: true,
      profileLoading: true,
      profile: {

      },
      active: 1,
      prev_page: false,
      next_page: false
    };

    this.profile = null;

    this.pageSize = 15;

    this.profileApi = defaultPostApi({
      __url: `sd/${ BlueWare.appId }/api/users/list`
    });

    this.sequenceApi = defaultPostApi({
      __url: `sd/${ BlueWare.appId }/api/events/sequence`
    });

    this.propertyApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/property/user/properties`
    });

    this.eventsApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/events/all`
    });

    this.eventPropsApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/property/all`
    });

    this.parameters = query.get();
  }

  componentWillMount() {
    this.fetchEvents();
    this.fetchProfile();
  }

  fetchProfile() {
    let cache = sessionStorage.getItem('sequence-user');

    this.propertyApi.fetch().then((res) => {
      if (_.isString(cache)) {
        let user = JSON.parse(cache);
        this.profile = user;

        let profile = _.omit(user, 'profiles', 'id');

        return _.extend({}, profile, user.profiles);
      }

      return (
        this.profileApi.post(config => {
          config.data = JSON.stringify({
            request_id: new Date().getTime(),
            use_cache: true,
            users: [this.props.params.uid]
          });

          config.contentType = 'application/json';

          return config;
        }).then((res) => {
          let users = _.first(res.users);

          let profiles = _.extend({}, {
            first_id: users.first_id,
            second_id: users.second_id
          }, users.profiles);

          this.profile = profiles;
        })
      );
    }).then((profiles) => {
      this.propertyApi.fetch().then((res) => {
        let result = {};

        _.forEach(profiles, (value, key) => {
          let property = _.find(res, (item) => {
            return key === item.name;
          });

          if (property) {
            result[property.cname] = value;
          } else {
            result[key] = value;
          }
        });
        this.state.profile = result;
      }).always(() => {
        this.setState({
          profileLoading: false
        });
      });
    });
  }

  fetchEvents() {
    this.eventsApi.fetch()
      .then(events => {
        this.sequenceApi.fetch(config => {
          config.contentType = 'application/json';

          config.data = JSON.stringify(this.getParams());

          return config;
        }).then((eventResponse) => {
          return (
            this.eventPropsApi.fetch().then((eventProps) => {
              return {
                eventProps: eventProps,
                eventResponse: eventResponse
              }
            })
          );
        }).then(({eventProps, eventResponse}) => {
          this.state.prev_page = eventResponse.prev_page;
          this.state.next_page = eventResponse.next_page;

          this.state.events = _.map(eventResponse.events, (event, index)  => {
            let result = {};
            result.time = event.time;
            result.mark = event.mark;
            result.event = _.find(events, (item) => {
              return item.name === event.event;
            }).cname;

            result.properties = covert(index, eventResponse.events, eventProps);

            return result;
          });
        }).always(() => {
          this.setState({
            eventLoading: false
          });
        });
      });
  }

  reload() {
    this.setState({
      eventLoading: true,
      profileLoading: true
    });

    this.fetchEvents();
    this.fetchProfile();
  }

  getParams(options = {}) {
    let parameters = _.extend({}, this.parameters, {
          'page': this.state.active - 1,
          'user_id': this.props.params.uid,
          'num_per_page': this.pageSize
        }, options);

    return parameters;
  }

  download() {
    this.refs.download.submit();
  }

  handlePaginate(number) {
    this.state.active += number;
    this.reload();
  }

  renderContent() {
    let prevPageHanler = this.state.prev_page ? { onClick: this.handlePaginate.bind(this, -1) } : null;
    let nextPageHanler = this.state.next_page ? { onClick: this.handlePaginate.bind(this,  1) } : null;

    return (
      <div className="widget-content">
        <div className="pure-g">
          <div className="pure-u-1 pure-u-xl-3-5">
            <div className="box">
              <div className="widget-normal">
                <h5>用户行为序列</h5>
                { this.state.eventLoading ? <Loading /> : (
                  <div>
                    <table className="table">
                      <thead>
                        <tr>
                          <th width="50%">时间</th>
                          <th width="50%">事件</th>
                        </tr>
                      </thead>
                      <tbody>
                        {
                          _.map(this.state.events, (event, key) => {
                            return (
                              <tr key={ key } className={ classnames({
                                'mark-shadow': event.mark
                              }) }>
                                <td>{ event.time.replace(/\.[\d]+/, '') }</td>
                                <td>
                                  <span data-tip={ renderToStaticMarkup(<PopoverCard properties={ event.properties } />) } key={ key } data-type="light" data-place="right">{ event.event }</span>
                                </td>
                              </tr>
                            )
                          })
                        }
                      </tbody>
                    </table>
                    <div className="paginate clearfix">
                      <a href="javascript:;" className={ classnames('prev-page', {
                        active: this.state.prev_page
                      }) } {...prevPageHanler}>向前</a>
                      <a href="javascript:;" className={ classnames('next-page', {
                        active: this.state.next_page
                      }) } {...nextPageHanler}>向后</a>
                    </div>
                  </div>
                ) }
              </div>
            </div>
          </div>
          <div className="pure-u-1 pure-u-xl-2-5">
            <div className="box">
              <div className="widget-normal">
                <h5>用户属性</h5>
                {
                  this.state.profileLoading ? <Loading /> : (
                    <div className="user-sequence-profile">
                      {
                        _.map(this.state.profile, (profile, key) => {
                          return (
                            <div className="clearfix profile-item" key={ key }>
                              <span className="label">{ key }: </span>
                              <span className="value" dangerouslySetInnerHTML={{__html: translator(profile)}}></span>
                            </div>
                          )
                        })
                      }
                    </div>
                  )
                }
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  render() {
    let {
      from_date,
      to_date
    } = this.parameters;

    return (
      <div className="box user-sequence">
        <div className="widget-float position-relative">
          <div className="widget-tools">
            <a className="iconfont icon-refresh" href="javascript:;" onClick={ this.reload.bind(this) }></a>
            <a className="iconfont icon-download" href="javascript:;" onClick={ this.download.bind(this) }></a>
          </div>
          <form
            action={ `/mobile/sd/${ BlueWare.appId }/api/events/sequence/csv` }
            ref="download"
            style={{display: 'none'}}
            acceptCharset="UTF-8"
            encType="application/x-www-form-urlencoded"
            target="_blank"
            method="POST">
            <input type="hidden" name="filename" value={`行为事件分析-用户列表-用户行为序列-${from_date}至${to_date}`} />
            <input type="hidden" name="form_data" value={ JSON.stringify(this.getParams({
              all_page: true
            })) } />
            <input type="hidden" name="detail" value={ JSON.stringify(this.profile) } />
          </form>
          <div className="widget-title">
            <a className="close iconfont" href="#/">&#xe638;</a>
            <h4><Link to={`/users/${this.props.location.search}`}>用户列表</Link> / 用户行为序列</h4>
          </div>
          { this.renderContent() }
        </div>
      </div>
    );
  }
}

export default UserSequenceView;
